package com.greenhouse.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfig {

    @Value("${mqtt.broker}")
    private String brokerUrl;

    @Value("${mqtt.client-id}")
    private String clientId;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.timeout}")
    private int timeout;

    @Value("${mqtt.keep-alive-interval}")
    private int keepAliveInterval;

    @Value("${mqtt.completion-timeout}")
    private int completionTimeout;

    public int getQos() {
        return qos;
    }

    public void setQos(int qos) {
        this.qos = qos;
    }

    @Value("${mqtt.qos}")
    private int qos;

    @Value("${mqtt.topic.sensors}")
    private String sensorsTopic;

    @Value("${mqtt.topic.images}")
    private String imagesTopic;

    @Value("${mqtt.topic.video}")
    private String videoTopic;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient client = new MqttClient(brokerUrl, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(timeout);
        options.setKeepAliveInterval(keepAliveInterval);
        options.setCleanSession(true);
        client.connect(options);
        return client;
    }

    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(timeout);
        options.setKeepAliveInterval(keepAliveInterval);
        options.setCleanSession(true);
        return options;
    }

    // 提供getter方法来访问这些topic
    public String getSensorsTopic() {
        return sensorsTopic;
    }

    public String getImagesTopic() {
        return imagesTopic;
    }

    public String getVideoTopic() {
        return videoTopic;
    }

}
